package com.um.jdy.ykc.command;

import cn.hutool.core.util.ClassUtil;
import com.um.jdy.ykc.utils.RadixsUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 命令工厂类
 *
 * @author 甘天伟
 * @since 2022/7/3
 * 版权所有 广州优匠科技有限公司
 */
@Slf4j
public class YkcCommandFactory {

    private static volatile Map<String, Class<?>> commandClasses = null;

    private static Map<String, Class<?>> getCommandClasses() {
        if (commandClasses == null) {
            synchronized (YkcCommandFactory.class) {
                if (commandClasses == null) {
                    commandClasses = new ConcurrentHashMap<>();
                    String packageName = YkcCommand.class.getPackage().getName();
                    Set<Class<?>> classes = ClassUtil.scanPackage(packageName, clazz -> clazz.getSimpleName().startsWith("Cmd"));
                    classes.forEach(clazz -> commandClasses.put(clazz.getSimpleName().substring(3, 5), clazz));
                }
            }
        }
        return commandClasses;
    }

    public static YkcCommand createCommand(byte[] bytes) {
        if (bytes.length < 8 || bytes[0] != 0x68) {
            return null;
        }

        String commandKey = RadixsUtil.byteToHexString(bytes[5]);
        Class<?> clazz = getCommandClasses().get(commandKey);
        if (clazz != null) {
            try {
                YkcCommand command = (YkcCommand) clazz.newInstance();
                command.parseBytes(bytes);
                return command;
            } catch (Exception e) {
                log.error("创建" + clazz.getSimpleName() + "实例出错", e);
            }
        }

        return null;
    }
}
